package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @author Amos
 * @date 2021/10/8
 */

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> findByNameAndSex(String name, String sex) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "王昭君")
                .eq("sex", "女");
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public List<User> findUserByNS(User user) {
        // Mybatis-Plus的特点，user对象中非空的属性作为where查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public List<User> getUserByIds(Integer[] ids) {
        return userMapper.selectBatchIds(Arrays.asList(ids));
    }

    @Override
    public List<User> getUserBySA(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sex", user.getSex())
                .gt("age", 18);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public List<User> getUser(User user) {
        // 根据对象中不为null的属性充当where条件
        return userMapper.selectList(new QueryWrapper<>(user));
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public void saveUser(User user) {
        userMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void updateUserByName(User user, String name) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("name", "小燕子");
        userMapper.update(user, updateWrapper);
    }
}
